package com.lsa.letcode.the19.removeNthAtEnd;

import com.lsa.letcode.common.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
    	if (n == 0) {
    		return head;
    	}
    	if (head == null) {
    		return null;
    	}
    	int i = 0;
    	ListNode ahead;
    	for(ahead = head; ahead != null && i < n; ahead = ahead.next, i++) {
    	}
    	
    	if (i < n) {
    		return head;
    	}
    	
    	ListNode prev = null;
    	ListNode cur = head;
    	
    	for(;ahead != null; ahead = ahead.next, prev = cur, cur = cur.next) {
    	}
    	
    	if (prev != null) {
    		prev.next = cur.next;
    	}
    	else {
    		head = head.next;
    	}
        return head;
    }
}